﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BLL.TcpUdp;
using BLL.Dataprogram;
using System.Collections.ObjectModel;
using System.Data;
using System.Windows.Threading;
using System.Threading;
using Framework.Kit;

namespace Client
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        DataTable dt = new DataTable();
        //用于记录出价次数
        int dtno = 0;
        private DispatcherTimer timer = new DispatcherTimer();
        DateTime currentTime = new System.DateTime();

        public MainWindow()
        {
            try
            {
                App.connect();
                this.Hide();
                login login = new login();
                if (login.ShowDialog() == true)
                {
                    dt.Columns.Add("CJ_no", typeof(int));
                    dt.Columns.Add("CJ_time", typeof(string));
                    dt.Columns.Add("CJ_add", typeof(string));
                    dt.Columns.Add("CJ_last", typeof(string));
                    dt.Columns.Add("CJ_isget", typeof(string));

                    timer.Tick += new EventHandler(timer_Tick);
                    timer.Interval = new TimeSpan(0, 0, 0, 1, 0);
                    timer.Start();
                    InitializeComponent();
                    //这里初始化页面上的数据，请保证使用前，数据已经从服务器内调回到(全局变量)
                    InitControlInfo();
                    this.Show();
                }
                else
                {
                    Application.Current.Shutdown();
                }
            }
            catch (Exception ex)
            {
                other.WriteErrLog("从开起来登录成功页面初始化", ex);
                MessageBox.Show(ex.ToString());
            }
            /**************************客户端事件***********************/
            App.client.ReceivedDatagram += new NetEvent(this.RecvData);
            App.client.DisConnectedServer += new NetEvent(this.ClientClose);
        }

        /*******************************客户端代码******************************/

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void RecvData(object sender, NetEventArgs e)
        {
            commandCtr cmdDp = new commandCtr();
            cmdDp.add = cmdDp_add;  //出价成功后所要运行的方法
            cmdDp.newmoney = cmdDP_newnoney;
            cmdDp.commandCtra(e);
            //string info = string.Format("recv data:{0} from:{1}.", e.Client.Datagram, e.Client);
        }
        /// <summary>
        /// 出价成功后修改页面出价信息
        /// </summary>
        /// <param name="a">出价行号，暂定只有这一个吧</param>
        void cmdDp_add(string a)
        {
            try
            {
                string[] arr1 = a.Split('|');  // 字符串变成数组
                dt.Rows[int.Parse(arr1[0])-1]["CJ_isget"] = "出价成功";
                DataView dv = new DataView(dt);
                dv.Sort = "CJ_no desc";
                this.userLV.Dispatcher.Invoke(new Action(() => { this.userLV.DataContext = dv.ToTable(); }));
            }
            catch (Exception ex)
            {
                other.WriteErrLog("出价成功后修改页面出价信息", ex);
            }
        }
        /// <summary>
        /// 出现新的最高价后修改页面最高价信息
        /// </summary>
        /// <param name="a">最高价|是否是本客户的出价(0,1)</param>
        void cmdDP_newnoney(string a)
        {
            try
            {
                string[] arr1 = a.Split('|');  // 字符串变成数组
                this.SP_thismoney.Dispatcher.Invoke(new Action(() => { this.SP_thismoney.Text = arr1[0]; }));
            }
            catch (Exception ex)
            {
                other.WriteErrLog("出现新的最高价后修改页面最高价信息", ex);
            }
        }
        /// <summary>
        /// 客户端退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ClientClose(object sender, NetEventArgs e)
        {
            string info;
            string msgStr;
            if (e.Client.TypeOfExit == Session.ExitType.ExceptionExit)
            {
                info = string.Format("A Client Session:{0} Exception Closed.",
                 e.Client.ID);
                msgStr = "服务器关闭,连接断开";
            }
            else
            {
                info = string.Format("A Client Session:{0} Normal Closed.",
                 e.Client.ID);
                msgStr = "已知关闭";
            }
            MessageBox.Show(msgStr);
            this.Close();
        }

        /// <summary>
        /// 窗体关闭操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 窗体帮助操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void helpBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 窗体拖拉操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //if (e.ChangedButton == MouseButton.Left) this.DragMove();
        }

        /// <summary>
        /// 最小化
        /// </summary>
        private void minBtn_Click(object sender, RoutedEventArgs e)
        {
            //
        }

        /// <summary>
        /// 关闭客户端
        /// </summary>
        private void closeBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //此函数是将int类型转变成类似"1,500,300"的字符串
        private string getitlive(int i)
        {
            string ai = i.ToString();
            for (int p = 3; p < i.ToString().Length; p++)
            {
                if (p % 3 == 0)
                {
                    ai = ai.Insert(i.ToString().Length - p, ",");
                }
            }
            return ai;
        }


        /// <summary>
        /// 初始化客户端值
        /// </summary>
        private void InitControlInfo()
        {
            this.Width = SystemParameters.WorkArea.Width;
            this.Height = SystemParameters.WorkArea.Height;
            this.Top = this.Left = 0;
            this.MaxHeight = this.MinHeight = this.Height;
            FMain.Width = this.MaxWidth = this.MinWidth = this.Width;
            FMain.Height = SystemParameters.WorkArea.Height - 190;
            this.goodssize.Height = FMain.Height - 50;
            this.JBsize.Width = FMain.Width - 450;
            this.userLV.Width = FMain.Width - 490;
            this.userLV.Height = FMain.Height - 450;
            this.userLVin.Height = this.userLV.Height - 25;
            if (this.Width > 1000) { this.BTXX.Width = 500; }

            //内容附值
            this.BMname.Content = App.BMname;
            this.SBname.Content = App.SBname;
            this.JBfunction.Content = App.JBfunction;
            this.BMtencher.Content = App.BMtencher;
            this.BMbegintime.Content = App.BMbegintime;
            this.JBaddmoney.Content = App.addmoney.ToString() + "元";
            this.SP_spname.Content = App.SBname;
            this.SP_spmoney.Content = App.SP_spmoney;
            this.SP_spLV.Content = App.SP_spLV;
            this.SP_thismoney.Text = App.SP_spmoney;
            this.SP_time.Text = "拍卖暂未开始";
            this.SP_button_buyonce.Content = " 竞拍加价一次\n\n（加价" + App.addmoney+"元 )";
            //商品图片定义
            System.Windows.Media.Imaging.BitmapImage image_uri = new System.Windows.Media.Imaging.BitmapImage();
            image_uri.BeginInit();
            string realPath = "resource/images/73.jpg";
            image_uri.UriSource = new Uri(realPath, UriKind.RelativeOrAbsolute);
            image_uri.EndInit();
            this.SP_image1.Source = image_uri;
        }

        /// <summary>
        /// 时间处理,用于显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void timer_Tick(object sender, EventArgs e)
        {
            currentTime = System.DateTime.Now;
            hour_0.SetResourceReference(Image.StyleProperty, "num_" + getOne(currentTime.Hour).Substring(0, 1));
            hour_1.SetResourceReference(Image.StyleProperty, "num_" + getOne(currentTime.Hour).Substring(1, 1));
            minute_0.SetResourceReference(Image.StyleProperty, "num_" + getOne(currentTime.Minute).Substring(0, 1));
            minute_1.SetResourceReference(Image.StyleProperty, "num_" + getOne(currentTime.Minute).Substring(1, 1));
            second_0.SetResourceReference(Image.StyleProperty, "num_" + getOne(currentTime.Second).Substring(0, 1));
            second_1.SetResourceReference(Image.StyleProperty, "num_" + getOne(currentTime.Second).Substring(1, 1));

            string s = "17:30:00";
            DateTime dt = DateTime.ParseExact(s, "HH:mm:ss", null);
            TimeSpan dtyp = dt - currentTime;

            djhour_0.SetResourceReference(Image.StyleProperty, "num_" + getOne(dtyp.Hours).Substring(0, 1));
            djhour_1.SetResourceReference(Image.StyleProperty, "num_" + getOne(dtyp.Hours).Substring(1, 1));
            djminute_0.SetResourceReference(Image.StyleProperty, "num_" + getOne(dtyp.Minutes).Substring(0, 1));
            djminute_1.SetResourceReference(Image.StyleProperty, "num_" + getOne(dtyp.Minutes).Substring(1, 1));
            djsecond_0.SetResourceReference(Image.StyleProperty, "num_" + getOne(dtyp.Seconds).Substring(0, 1));
            djsecond_1.SetResourceReference(Image.StyleProperty, "num_" + getOne(dtyp.Seconds).Substring(1, 1));
        }
        /// <summary>
        /// 用于时间输出时的格式处理
        /// </summary>
        /// <param name="num">5</param>
        /// <returns>05</returns>
        string getOne(int num)
        {
            if (num < 0)
            {
                return "00";
            }
            if (num < 10)
            {
                return string.Format("{0:00}", num);
            }
            else
            {
                return num.ToString();
            }
        }
        //________页面上的按钮__________________________
        //加价一次
        private void btnAddCJ_Click(object sender, RoutedEventArgs e)
        {
            userLVown(DateTime.Now.ToString("HH:mm:ss"), App.addmoney, (App.addmoney + App.maxmoney).ToString(), "等待回复");

            sendtoseraddmoney((App.addmoney + App.maxmoney).ToString(), dtno);
        }
        /// <summary>
        /// 用于处理规定时间内服务器未有响应出价
        /// </summary>
        private void btnAddCJ_Click_isSend()
        {
            int dtnonow = dtno - 1;
            Thread.Sleep(App.timespan);
            if (dt.Rows[dtnonow]["CJ_isget"].ToString() == "等待回复")
            {
                dt.Rows[dtnonow]["CJ_isget"] = "失败：服务器未响应";
                try
                {
                    DataView dv = new DataView(dt);
                    dv.Sort = "CJ_no desc";
                    this.userLV.Dispatcher.Invoke(new Action(() => { this.userLV.DataContext = dv.ToTable(); }));
                }
                catch { 
                    MessageBox.Show("请不要过快点击");
                }
            }
            Thread.CurrentThread.Abort();
        }

        /// <summary>
        /// 加价操作
        /// </summary>
        /// <param name="lastmoney"></param>
        /// <param name="dtno"></param>
        private void sendtoseraddmoney(string lastmoney, int dtno)
        {
            int dtnonow = dtno;
            //App.sendData(commandType.c006, dtnonow.ToString() + "|" + lastmoney);
            Thread myThread = new Thread(new ThreadStart(btnAddCJ_Click_isSend));
            myThread.Start();
        }


        /// <summary>
        /// 在拍卖显示表内显示数据
        /// </summary>
        private void userLVown(string time, int add, string outmoeny, string isok)
        {
            dtno++;
            dt.Rows.Add(dtno, time, add, outmoeny, isok);
            DataView dv = new DataView(dt);
            dv.Sort = "CJ_no desc";
            this.userLV.DataContext = dv.ToTable();
        }
    }
}
